<template>
  <div class="patient-select-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-content">
        <div class="back-btn" @click="$router.go(-1)">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M15 18l-6-6 6-6"/>
          </svg>
        </div>
        <div class="header-title">第四步: 选择就诊人</div>
        <div class="home-btn" @click="$router.push('/')">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
            <polyline points="9,22 9,12 15,12 15,22"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="content">
      <div class="page-title">选择就诊人</div>
      <div class="page-subtitle">选择就诊人</div>

      <!-- 就诊人列表 -->
      <div class="patient-list">
        <div 
          v-for="patient in patients" 
          :key="patient.id"
          class="patient-card"
          :class="{ 'selected': selectedPatientId === patient.id }"
          @click="selectPatient(patient)"
        >
          <div class="patient-avatar">
            <img 
              :src="patient.avatar" 
              :alt="patient.name"
              @error="handleImageError"
              @load="() => console.log('图片加载成功:', patient.name)"
            />
          </div>
          <div class="patient-info">
            <div class="patient-name">{{ patient.name }}</div>
            <div class="patient-date">{{ patient.birthDate }}</div>
            <div class="patient-tag">标签</div>
          </div>
        </div>

        <!-- 添加就诊人 -->
        <div class="add-patient-card" @click="addPatient">
          <div class="add-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#1877F2" stroke-width="2">
              <line x1="12" y1="5" x2="12" y2="19"/>
              <line x1="5" y1="12" x2="19" y2="12"/>
            </svg>
          </div>
          <div class="add-text">添加就诊人</div>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-button">
      <button 
        class="next-btn" 
        :class="{ 'disabled': !selectedPatientId }"
        @click="goToNextStep"
        :disabled="!selectedPatientId"
      >
        下一步
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { localPatientsStorage, patientsApi, type Patient as ApiPatient } from '../../api/patients'

const router = useRouter()

interface Patient {
  id: string
  name: string
  birthDate: string
  gender: 'male' | 'female'
  idCard: string
  phone: string
  avatar: string
}

const patients = ref<ApiPatient[]>([])

const selectedPatientId = ref<string>('')

// 选择就诊人
const selectPatient = (patient: ApiPatient) => {
  selectedPatientId.value = patient.id
  
  try {
    localStorage.setItem('selectedPatientId', patient.id)
    
    // 只保存必要的信息，不包含头像数据
    const patientInfo = {
      id: patient.id,
      name: patient.name,
      birthDate: patient.birthDate,
      gender: patient.gender,
      idCard: patient.idCard,
      phone: patient.phone
    }
    localStorage.setItem('selectedPatient', JSON.stringify(patientInfo))
    showToast(`已选择就诊人：${patient.name}`)
  } catch (error) {
    console.error('保存就诊人信息失败:', error)
    // 即使保存失败，也允许选择就诊人
    showToast(`已选择就诊人：${patient.name}`)
  }
}

// 添加就诊人
const addPatient = () => {
  router.push('/add-patient')
}



// 下一步
const goToNextStep = () => {
  if (!selectedPatientId.value) {
    showToast('请选择就诊人')
    return
  }

  // 保存预约数据
  const appointmentData = localStorage.getItem('appointmentData')
  if (appointmentData) {
    const data = JSON.parse(appointmentData)
    const selectedPatient = patients.value.find(p => p.id === selectedPatientId.value)
    
    if (selectedPatient) {
      // 只保存必要的信息，不包含头像数据
      const patientInfo = {
        id: selectedPatient.id,
        name: selectedPatient.name,
        birthDate: selectedPatient.birthDate,
        gender: selectedPatient.gender,
        idCard: selectedPatient.idCard,
        phone: selectedPatient.phone
      }
      data.patient = patientInfo
      
      try {
        localStorage.setItem('appointmentData', JSON.stringify(data))
      } catch (error) {
        console.error('保存预约数据失败:', error)
        // 即使保存失败，也允许继续
      }
    }
  }

  // 跳转到预约确认页面
  router.push('/appointment-confirm')
}

// 轻提示
const showToast = (message: string) => {
  const toast = document.createElement('div')
  toast.className = 'toast-message'
  toast.textContent = message
  document.body.appendChild(toast)
  
  setTimeout(() => toast.classList.add('show'), 10)
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => {
      if (document.body.contains(toast)) {
        document.body.removeChild(toast)
      }
    }, 300)
  }, 3000)
}

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.log('图片加载失败，使用默认头像:', img.src)
  img.src = ''
}

onMounted(async () => {
  try {
    // 尝试从后端API获取就诊人数据
    const response = await patientsApi.getPatients()
    if (response.success && response.data.length > 0) {
      patients.value = response.data
      // 同步到本地存储
      response.data.forEach((patient: ApiPatient) => localPatientsStorage.savePatient(patient))
    } else {
      // 如果后端没有数据，从本地存储加载
      const localPatients = localPatientsStorage.getPatients()
      if (localPatients.length > 0) {
        patients.value = localPatients
      } else {
        // 如果本地也没有数据，添加默认数据
        const defaultPatients: ApiPatient[] = [
          {
            id: '1',
            name: '王小样',
            birthDate: '2011-11-25',
            gender: 'male',
            idCard: '110101201111251234',
            phone: '13800138000',
            avatar: '',
            createdAt: '2024-01-01T00:00:00.000Z',
            updatedAt: '2024-01-01T00:00:00.000Z'
          },
          {
            id: '2',
            name: '大毛蛋',
            birthDate: '2011-11-26',
            gender: 'female',
            idCard: '110101201111261234',
            phone: '13800138001',
            avatar: '',
            createdAt: '2024-01-01T00:00:00.000Z',
            updatedAt: '2024-01-01T00:00:00.000Z'
          }
        ]
        patients.value = defaultPatients
        // 保存默认数据到本地存储
        defaultPatients.forEach(patient => localPatientsStorage.savePatient(patient))
      }
    }
  } catch (error) {
    console.error('获取就诊人数据失败:', error)
    // 网络错误时从本地存储加载
    const localPatients = localPatientsStorage.getPatients()
    if (localPatients.length > 0) {
      patients.value = localPatients
    }
  }
  
  // 从本地存储恢复选中状态
  const savedPatientId = localStorage.getItem('selectedPatientId')
  if (savedPatientId) {
    selectedPatientId.value = savedPatientId
  }
  
  console.log('PatientSelect页面初始化完成，就诊人数量:', patients.value.length)
  patients.value.forEach((patient, index) => {
    console.log(`就诊人${index + 1}:`, patient.name, '头像长度:', patient.avatar?.length || 0)
  })
  
  // 检查localStorage配额
  try {
    const testKey = 'storage_test'
    const testValue = 'x'.repeat(1024) // 1KB测试
    localStorage.setItem(testKey, testValue)
    localStorage.removeItem(testKey)
  } catch (error) {
    console.warn('localStorage配额可能不足，建议清理浏览器数据')
    showToast('存储空间不足，建议清理浏览器数据')
  }
})
</script>

<style scoped>
.patient-select-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 100px;
}

.header {
  background: #1877F2;
  padding: 0 20px;
  padding-top: env(safe-area-inset-top);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
}

.back-btn, .home-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.2s;
}

.back-btn:hover, .home-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.header-title {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.content {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 4px;
}

.page-subtitle {
  font-size: 14px;
  color: #999;
  margin-bottom: 24px;
}

/* 就诊人列表 */
.patient-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.patient-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.2s;
  border: 2px solid transparent;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.patient-card:hover {
  box-shadow: 0 4px 12px rgba(24,119,242,0.15);
}

.patient-card.selected {
  border-color: #1877F2;
  background: #f8fbff;
  box-shadow: 0 4px 16px rgba(24,119,242,0.2);
}

.patient-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  background: linear-gradient(135deg, #00D4FF 0%, #5B73FF 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.patient-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.patient-info {
  flex: 1;
}

.patient-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.patient-date {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.patient-tag {
  display: inline-block;
  background: #1877F2;
  color: white;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 500;
}

/* 添加就诊人卡片 */
.add-patient-card {
  background: white;
  border: 2px dashed #ddd;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.add-patient-card:hover {
  border-color: #1877F2;
  background: #f8fbff;
}

.add-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.add-text {
  font-size: 16px;
  font-weight: 500;
  color: #1877F2;
}

/* 底部按钮 */
.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.next-btn {
  width: 100%;
  height: 48px;
  background: #1877F2;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.next-btn:hover:not(.disabled) {
  background: #1565c0;
}

.next-btn.disabled {
  background: #ccc;
  color: #999;
  cursor: not-allowed;
}



/* 轻提示 */
.toast-message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  z-index: 10000;
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  white-space: nowrap;
}

.toast-message.show {
  opacity: 1;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .content {
    padding: 16px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .patient-card {
    padding: 12px;
  }
  
  .patient-avatar {
    width: 50px;
    height: 50px;
  }
  
  .modal-content {
    width: 95%;
  }
}
</style> 